package com.ott.tool;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JOptionPane;

import com.ott.Util.BaseUtil;
import com.ott.Util.FileUtil;



public class ButtonAction implements ActionListener {
	
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton button = (JButton) e.getSource();
		String tomcatpath = IndexForm.tomcatpath;
		String FilePath = IndexForm.FilePath;
		IndexForm.textArea.append("------------START----------\r\n");
		if (button.getText().contains("初始化")) {
			int ifadd = JOptionPane.showConfirmDialog(null, "确定吗？", "提示！", JOptionPane.YES_NO_OPTION);
			if (ifadd == JOptionPane.YES_OPTION) {
				
				File file = new File(IndexForm.textArea2.getText());
				if(file.isDirectory()){
					LinkedList<File> list = new LinkedList<File>();
					LinkedList<String> sqllist = new LinkedList<String>();
					File[] files = file.listFiles();
					for (File file2 : files) {
						String fileName=file2.getName();
					    String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
					    if(prefix.equals("war")){
					    	list.add(file2);
					    }else if(prefix.equals("sql")){
					    	sqllist.add(fileName);
					    }
					}
					
					if(list.size() > 0){
						
						IndexForm.textArea.append("==========停止tomcat=========\r\n");
						//停止tomcat
						IndexForm.textArea.append("==========停止tomcat脚本开始执行=========\r\n");
						//停止tomcat
						try {
							//Boolean flag = (new StartAndStopTomcat()).execShell(tomcatpath+"bin/shutdown.bat");
							Boolean flag = (new ExecShell()).execShell(IndexForm.shellPathString+"stopTomcat.sh");
							if(flag){
								IndexForm.textArea.append("==========停止tomcat脚本执行成功=========\r\n");
							}else{
								IndexForm.textArea.append("==========停止tomcat脚本执行失败=========\r\n");
							}
						} catch (Exception e2) {
							IndexForm.textArea.append("==========停止tomcat失败=========\r\n"+e2);
						}
						
						File f = new File(FilePath+"config/");
						if (!f.exists()) {
					            f.mkdirs();
					        }
					    f = new File(FilePath+"config/config.properties");
					        // 创建文件
				        if (!f.exists()) {
				            try {
				                f.createNewFile();
				            } catch (IOException e1) {
				                e1.printStackTrace();
				            }
				        }
						//参数为要修改的文件路径  以及要修改的属性名和属性值 
				        //读取播控IP地址
				        IndexForm.textArea.append("开始生成外部配置文件 config.properties\r\n");
						Boolean boolean1 = UpdateFile.updatePro(FilePath+"config/config.properties","ip",IndexForm.field.getText());
						if(boolean1){
							IndexForm.textArea.append("外部配置文件 config.properties 生成成功\r\n");
						}else{
							IndexForm.textArea.append("外部配置文件 config.properties 生成失败\r\n");
						}
						File f2 = new File("/opt/tms/upfinish/1.0.0/");
						if (!f2.exists()) {
					            f2.mkdirs();
				        }
						String warPath = FilePath + "upfinish/1.0.0/";
						Boolean boolean2 = false;
						for (File file2 : list) {
							File file3 = new File(warPath+file2.getName());
							if(file3.exists()){
								file3.delete();
							}
//							//移动分割日志文件到指定目录
//							if(file2.getName().equals("cronosplit")||file2.getName().equals("cronolog")){
//								File file4 = new File("/usr/local/sbin/");
//								if (!file4.exists()) {
//									file4.mkdir();
//								}
//								file2.renameTo(new File("/usr/local/sbin/"+file2.getName()));
//							}
							boolean2 = FileUtil.copyFile(IndexForm.textArea2.getText()+file2.getName(),warPath+file2.getName());
							if(boolean2){
								IndexForm.textArea.append(file2.getName()+"移动成功\r\n");
								
								//删除war包
								File file4 = new File(tomcatpath+"webapps/"+file2.getName());
								if(file4.exists()){
									boolean2 = FileUtil.deleteDir(file4);
									if(boolean2){
										IndexForm.textArea.append(file2.getName()+"删除成功\r\n");
									}else{
										IndexForm.textArea.append(file2.getName()+"删除失败\r\n");
										break;
									}
								}
								
								//删除映射文件夹
								File directory = new File(tomcatpath+"webapps/"+file2.getName().substring(0,file2.getName().lastIndexOf(".")));
								if(directory.exists()){
									boolean2 = FileUtil.deleteDir(directory);
									if(boolean2){
										IndexForm.textArea.append(file2.getName()+"映射文件删除成功\r\n");
									}else{
										IndexForm.textArea.append(file2.getName()+"映射文件删除失败\r\n");
										break;
									}
								}
							}else {
								IndexForm.textArea.append(file2.getName()+"移动失败\r\n");
								break;
							}
						}
						if(boolean2){
							//生成tomcat的配置文件xml
							CreateXmlUtil cXmlUtil = new CreateXmlUtil();
							for (File file2 : list) {
								try {
									IndexForm.textArea.append("开始生成"+file2.getName().substring(0,file2.getName().lastIndexOf("."))+".xml\r\n");
									cXmlUtil.createXML(file2.getName().substring(0,file2.getName().lastIndexOf(".")),warPath+file2.getName(),tomcatpath+"conf/Catalina/localhost/");
									IndexForm.textArea.append(file2.getName().substring(0,file2.getName().lastIndexOf("."))+".xml生成成功\r\n");
								} catch (IOException e1) {
									IndexForm.textArea.append("tomcat的XML配置文件生成失败："+e1+"\r\n");
									break;
								}
							}
						}
						//执行sql文件
						if(sqllist.size()>0){
							IndexForm.textArea.append("开始执行sql脚本\r\n");
							for (int i = 0; i < sqllist.size(); i++) {
								ScriptRunnerExecSql sres = new ScriptRunnerExecSql();
								sres.execSql(IndexForm.textArea2.getText()+"/"+sqllist.get(i));
							}
							IndexForm.textArea.append("sql脚本执行结束\r\n");
						}else{
							IndexForm.textArea.append("文件夹中不存在sql文件\r\n");
						}
						
						// 执行shell脚本：同步服务器时区 时间,调用日志拆分脚本,调用定时删除日志脚本
						IndexForm.textArea.append("==========开始执行日志拆分、删除、同步时间shell脚本=========\r\n");
						Boolean flag = (new ExecShell()).execShell(IndexForm.shellPathString+"deletelog.sh");
						if (flag) {
							IndexForm.textArea.append("==========shell脚本执行完成=========\r\n");
						}else {
							IndexForm.textArea.append("==========shell脚本执行失败=========\r\n");
						}
						//启动tomcat
						try {
							IndexForm.textArea.append("==========启动tomcat脚本开始执行=========\r\n");
//								flag = (new StartAndStopTomcat()).execShell(tomcatpath+"bin/startup.bat");
							flag = (new ExecShell()).execShell(IndexForm.shellPathString+"startTomcat.sh");
							if(flag){
								IndexForm.textArea.append("==========启动tomcat脚本执行成功=========\r\n");
								IndexForm.textArea.append("==========开始启动py脚本=========\r\n");
								flag = (new ExecShell()).execShell("/opt/initver/py.sh");
								if (flag) {
									IndexForm.textArea.append("==========py脚本启动成功=========\r\n");
								}else{
									IndexForm.textArea.append("==========py脚本启动失败=========\r\n");
								}
							}else{
								IndexForm.textArea.append("==========启动tomcat脚本执行失败=========\r\n");
							}
							//上报云端
							String url = "http://192.168.1.242:8082/mts/versionUpdate/feedback.json";
							ReportInfo.reportMts(url);
							IndexForm.textArea.append("初始化完成\r\n");
						} catch (Exception e2) {
							IndexForm.textArea.append("==========启动tomcat脚本执行失败=========\r\n");
						}
						
					}else{
						IndexForm.textArea.append("请选择正确的文件夹\r\n");
						return;
					}
					
				}
			} else {
				IndexForm.textArea.append("初始化失败\r\n");
			}
		}
	}
}